package com.ytrsoft.io;

import com.ytrsoft.bean.IOType;

import java.io.OutputStream;
import java.io.PrintStream;

public class ProcessOutputStream extends PrintStream {

    private IOType type;
    private ProcessOutputStreamListener listener;

    public ProcessOutputStream(OutputStream out) {
        super(out, true);
        this.type = IOType.STDOUT;
        if (out.equals(System.err)) {
            this.type = IOType.STDERR;
        }
    }

    @Override
    public void write(byte[] buf, int off, int len) {
        super.write(buf, off, len);
        String s = new String(buf, off, len);
        // \r => \r\n
        s = s.replaceAll("(?<!\\r)\\n", "\r\n");
        // \n => \r\n
        s = s.replaceAll("\\r(?!\\n)", "\r\n");
        writeForData(s);
    }

    public void setOnProcessOutputStreamListener(ProcessOutputStreamListener listener) {
        this.listener = listener;
    }

    private void writeForData(String body) {
        if (this.listener != null) {
            this.listener.out(type, body);
        }
    }

}